var page="1";
var pageSize="10";

$(function () {
    //获取表格数据
    getUserList();
    layui.use('form', function () {
        var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
    });

})

/**
 * 后台返回数据填充表格 demo
 */
function getUserList() {
    var user={};
    if ($("#departmentId").val() != "" && $("#departmentId").val() != null){
        user.departmentId=$("#departmentId").val();
    }
    if ($("#departmentName").val() != "" && $("#departmentName").val() != null){
        user.departmentName=$("#departmentName").val();
    }
    if ($("#userName").val() != "" && $("#userName").val() != null){
        user.userName=$("#userName").val();
    }
    var department={}
    $.ajax({
        url: sessionStorage.getItem("rootPath")+ "/departments/selectDepartmentList",
        method: "post",
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(department),
        success: function (res) {
            renderTable(res);
            renderpage(res);
            console.log(res);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("失败" + XMLHttpRequest.status + ":" + textStatus + ":" + errorThrown);
        }
    })
}

/**
 * 表格渲染
 */
function renderTable(data) {
    layui.use('table', function () {
        var table = layui.table;
        table.render({
            elem: '#usersTable'
            ,url: '../../admin/data/common.json'
            , page: false
            , height: 400
            ,toolbar: '#toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: []
            , parseData: function (res) {
                return {
                    "code": 0,
                    "msg": "",
                    "data": data.data
                }
            }
            , cols: [[
                 {field: 'departmentName', title: '部门名称'}
                , {field: 'admins', title: '管理员',}
                , {fixed: 'right', title: '操作',templet:function (data) {
                        var btns = "";
                            btns += ' <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                            btns += ' <a class="layui-btn layui-btn-xs layui-btn layui-btn-primary" lay-event="modify"><i class="layui-icon layui-icon-util"></i>修改</a>';
                        return btns;
                    }}
            ]]
        });

        //监听行工具事件
        table.on('tool(usersDemo)', function (obj) {
            var data = obj.data;
            console.log(data);
            if (obj.event === 'delete'){
                layer.confirm('真的删除该部门吗？（注意！该部门资源库的文件也将删除）', function(index){
                    obj.del();
                    deleteUser(data.id);
                    layer.close(index);
                });
            }
            if (obj.event === 'modify'){
                    var departmentId = $(obj).parents("tr").find(".departmentId").text();
                    /*var name = department.name;*/
                    console.log(departmentId);
                    json = JSON.stringify(data);
	                layer.open({
                        type: 2,
                        title: '修改部门',
                        skin: 'layui-layer-molv', //样式类名
                        shade: 0.8,
                        shadeClose:false,
                        area: ['30%', '30%'],
                        content: 'modifyDepartment.html',
                             success:function(layero,index){
	                                     var body = layer.getChildFrame('body',index);
                                         body.find('from').find('#show_id').html(departmentId);
                                         /*console.log(body.html());*/
                                         console.log(departmentId);
                             }
                    });
            }
        });
    });
}
/**
 * 删除部门
 */
function deleteUser(id) {
    $.ajax({
        url:sessionStorage.getItem("rootPath") + "/departments/deleteDepartment",
        data:JSON.stringify(id),
        dataType:'json',
        contentType: 'application/json;charset=utf-8',
        type:'post',
        success:function(res){
            layer.msg("删除部门成功！",{icon:1,time:1000});
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.msg("删除部门失败！" ,{icon:2,time:1000});
            console.log("失败" + XMLHttpRequest.status + ":" + textStatus + ":" + errorThrown);
        }
    })
}
/**
 * 分页
 */
/*function renderpage(date) {
    layui.use('laypage', function () {
        var laypage = layui.laypage;

        //执行一个laypage实例
        laypage.render({
            elem: 'usersTable_page' //注意，这里的 test1 是 ID，不用加 # 号
            , layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
            , count: date.total //数据总数，从服务端得到
            , limits: [10,20, 30]
            , curr: page
            , limit: pageSize
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    page = obj.curr;
                    pageSize = obj.limit;
                    getUserList();
                }
            }
        });

    });
}*/

/**
 * 弹窗新增
 */
function showAddWin() {
    layui.use('layer', function () { //独立版的layer无需执行这一句
        var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
        layer.open({
            type: 2,
            title: '新增部门',
            skin: 'layui-layer-molv', //样式类名
            shade: 0.8,
            shadeClose:false,
            area: ['30%', '30%'],
            content: 'addDepartment.html'
        });
    });
}

function getDepartmentId(){
	var department={};
	department.Id = document.getElementById("depaertmentId");
	department.Name = document.getElementById("depaertmentName");
	console.log(department);
	return department;
}
